package com.hy.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.reggie.dto.DishDto;
import com.hy.reggie.mapper.DishMapper;
import com.hy.reggie.pojo.Dish;
import com.hy.reggie.pojo.DishFlavor;
import com.hy.reggie.service.DishFlavorService;
import com.hy.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void add(DishDto dishDto) {
        //新增菜品，同时插入对应口味
        this.save(dishDto);

        //菜品id
        Long dishId = dishDto.getId();

        //保存菜品口味数据到口味表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor : flavors) {
            dishFlavor.setDishId(dishId);
        }

        dishFlavorService.saveBatch(flavors);

        //清理缓存(所有)
        Set<String> keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishDto selectOne(Long id) {
        //获取菜品信息
        Dish dish = this.getById(id);
        //获取口味信息
        DishDto dishDto = JSON.parseObject(JSON.toJSONString(dish), DishDto.class);
        //条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        //根据菜品id查询口味
        queryWrapper.eq(DishFlavor::getDishId, id);

        List<DishFlavor> dishFlavors = dishFlavorService.getBaseMapper().selectList(queryWrapper);

        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }

    /**
     * 修改菜品和口味
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateDishAndFlavor(DishDto dishDto) {
        //修改菜品，同时插入对应口味
        this.updateById(dishDto);

        //菜品id
        Long dishId = dishDto.getId();

        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();

        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);

        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //保存菜品口味数据到口味表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor : flavors) {
            dishFlavor.setDishId(dishId);
        }

        dishFlavorService.saveBatch(flavors);

    }


}
